#include <stdio.h>
#include "lua.h"
#include "lauxlib.h"

static int l_test (lua_State *L) {
    printf("hello world\n");
    return 0;
}

static int l_map(lua_State *L) {
	luaL_checktype(L, 1, LUA_TTABLE);
	luaL_checktype(L, 2, LUA_TFUNCTION);
	int len = luaL_len(L, 1);
	lua_createtable(L, len, 0);
	for (int i = 1; i <= len; ++i) {
		lua_pushvalue(L, 2);
		lua_geti(L, 1, i);
		lua_call(L, 1, 1);
		lua_seti(L, 3, i);
	}

	return 1;
}

static const struct luaL_Reg mylib [] = {
    {"test", l_test},
	{"map", l_map}, 
    {NULL, NULL}
};

// loader函数
int luaopen_mylib(lua_State *L) {
    // 新建一个库(table)，把函数加入这个库中，并返回
    luaL_newlib(L, mylib);
    return 1;
}

